<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PDF拆分工具</title>
    <script src="https://unpkg.com/pdf-lib@1.17.1/dist/pdf-lib.min.js"></script>
    <script src="https://unpkg.com/downloadjs@1.4.7"></script>
    <style>
        :root {
            --primary-color: #4a6fa5;
            --secondary-color: #6c8fc7;
            --background-color: #f5f7fa;
            --text-color: #333;
            --border-color: #ddd;
            --error-color: #e74c3c;
            --success-color: #2ecc71;
        }
        
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        body {
            background-color: var(--background-color);
            color: var(--text-color);
            line-height: 1.6;
            padding: 20px;
        }
        
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        
        h1 {
            text-align: center;
            margin-bottom: 20px;
            color: var(--primary-color);
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
        }
        
        input[type="file"],
        input[type="text"],
        input[type="number"] {
            width: 100%;
            padding: 10px;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            font-size: 16px;
        }
        
        input[type="file"] {
            padding: 8px;
        }
        
        .btn {
            background-color: var(--primary-color);
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s;
        }
        
        .btn:hover {
            background-color: var(--secondary-color);
        }
        
        .btn-secondary {
            background-color: #6c757d;
        }
        
        .btn-secondary:hover {
            background-color: #5a6268;
        }
        
        .range-row {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }
        
        .range-row input {
            width: 80px;
            margin: 0 10px;
            text-align: center;
        }
        
        .range-row .remove-range {
            background-color: var(--error-color);
            color: white;
            border: none;
            width: 30px;
            height: 30px;
            border-radius: 50%;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-left: 10px;
        }
        
        .actions {
            display: flex;
            gap: 10px;
            margin-top: 20px;
        }
        
        #addRange {
            margin-bottom: 20px;
        }
        
        #status {
            margin-top: 20px;
            padding: 10px;
            border-radius: 4px;
            display: none;
        }
        
        .error {
            background-color: #f8d7da;
            color: var(--error-color);
            display: block !important;
        }
        
        .success {
            background-color: #d4edda;
            color: var(--success-color);
            display: block !important;
        }
        
        .pdf-info {
            margin-top: 20px;
            padding: 15px;
            background-color: #f8f9fa;
            border-radius: 4px;
            border-left: 4px solid var(--primary-color);
        }
        
        #loading {
            display: none;
            margin-top: 20px;
            text-align: center;
        }
        
        .spinner {
            border: 4px solid rgba(0, 0, 0, 0.1);
            border-radius: 50%;
            border-top: 4px solid var(--primary-color);
            width: 30px;
            height: 30px;
            animation: spin 1s linear infinite;
            margin: 0 auto 10px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>PDF拆分工具</h1>
        
        <div class="form-group">
            <label for="pdfFile">选择PDF文件</label>
            <input type="file" id="pdfFile" accept=".pdf">
        </div>
        
        <div id="pdfInfo" class="pdf-info" style="display: none;">
            <p>文件名: <span id="fileName"></span></p>
            <p>页数: <span id="pageCount"></span></p>
        </div>
        
        <div class="form-group">
            <label>拆分设置</label>
            <div id="rangeContainer">
                <div class="range-row">
                    <span>范围 1:</span>
                    <input type="number" class="start-page" placeholder="起始页" min="1">
                    <span>至</span>
                    <input type="number" class="end-page" placeholder="结束页" min="1">
                    <button class="remove-range" onclick="removeRange(this)">×</button>
                </div>
            </div>
            <button id="addRange" class="btn btn-secondary" onclick="addRange()">添加范围</button>
        </div>
        
        <div class="actions">
            <button id="splitBtn" class="btn" onclick="splitPDF()" disabled>开始拆分</button>
            <button id="resetBtn" class="btn btn-secondary" onclick="resetForm()">重置</button>
        </div>
        
        <div id="loading">
            <div class="spinner"></div>
            <p>正在处理PDF，请稍候...</p>
        </div>
        
        <div id="status" class="status"></div>
    </div>

    <script>
        let pdfBytes = null;
        let totalPages = 0;
        let rangeCounter = 1;
        let fileName = '';
        
        // 文件选择变化时
        document.getElementById('pdfFile').addEventListener('change', async function(e) {
            const file = e.target.files[0];
            if (!file) return;
            
            fileName = file.name.replace('.pdf', '');
            document.getElementById('fileName').textContent = file.name;
            
            showLoading(true);
            
            try {
                const arrayBuffer = await file.arrayBuffer();
                pdfBytes = new Uint8Array(arrayBuffer);
                
                // 加载PDF文档获取页数
                const pdfDoc = await PDFLib.PDFDocument.load(pdfBytes);
                totalPages = pdfDoc.getPageCount();
                
                document.getElementById('pageCount').textContent = totalPages;
                document.getElementById('pdfInfo').style.display = 'block';
                document.getElementById('splitBtn').disabled = false;
                
                showStatus('PDF文件加载成功', 'success');
            } catch (error) {
                showStatus('加载PDF失败: ' + error.message, 'error');
            } finally {
                showLoading(false);
            }
        });
        
        // 添加范围行
        function addRange() {
            rangeCounter++;
            const rangeContainer = document.getElementById('rangeContainer');
            const newRange = document.createElement('div');
            newRange.className = 'range-row';
            newRange.innerHTML = `
                <span>范围 ${rangeCounter}:</span>
                <input type="number" class="start-page" placeholder="起始页" min="1">
                <span>至</span>
                <input type="number" class="end-page" placeholder="结束页" min="1">
                <button class="remove-range" onclick="removeRange(this)">×</button>
            `;
            rangeContainer.appendChild(newRange);
        }
        
        // 删除范围行
        function removeRange(button) {
            const rangeContainer = document.getElementById('rangeContainer');
            if (rangeContainer.children.length > 1) {
                button.parentNode.remove();
                // 重新编号
                const ranges = rangeContainer.getElementsByClassName('range-row');
                for (let i = 0; i < ranges.length; i++) {
                    ranges[i].firstChild.textContent = `范围 ${i + 1}:`;
                }
                rangeCounter = ranges.length;
            } else {
                showStatus('至少需要保留一个范围', 'error');
            }
        }
        
        // 拆分PDF
        async function splitPDF() {
            if (!pdfBytes) {
                showStatus('请先选择PDF文件', 'error');
                return;
            }
            
            const ranges = [];
            const rangeRows = document.getElementById('rangeContainer').getElementsByClassName('range-row');
            let isValid = true;
            
            // 收集所有范围
            for (let i = 0; i < rangeRows.length; i++) {
                const startInput = rangeRows[i].querySelector('.start-page');
                const endInput = rangeRows[i].querySelector('.end-page');
                
                const start = parseInt(startInput.value);
                const end = parseInt(endInput.value);
                
                if (isNaN(start) || isNaN(end)) {
                    showStatus(`范围 ${i + 1} 的页数无效`, 'error');
                    isValid = false;
                    break;
                }
                
                if (start < 1 || end > totalPages || start > end) {
                    showStatus(`范围 ${i + 1} (${start}-${end}) 超出PDF页数范围 (1-${totalPages})`, 'error');
                    isValid = false;
                    break;
                }
                
                ranges.push({ start, end });
            }
            
            if (!isValid) return;
            
            showLoading(true);
            showStatus('正在拆分PDF...', 'info');
            
            try {
                // 拆分PDF
                await splitPDFIntoRanges(ranges);
                showStatus(`成功拆分PDF为 ${ranges.length} 个文件`, 'success');
            } catch (error) {
                showStatus('拆分PDF时出错: ' + error.message, 'error');
                console.error(error);
            } finally {
                showLoading(false);
            }
        }
        
        // 实际拆分PDF
        async function splitPDFIntoRanges(ranges) {
            // 加载原始PDF
            const originalPdfDoc = await PDFLib.PDFDocument.load(pdfBytes);
            
            // 对于每个范围，创建一个新的PDF
            for (const range of ranges) {
                // 创建新的PDF文档
                const newPdfDoc = await PDFLib.PDFDocument.create();
                
                // 复制指定页面到新文档
                const pages = await newPdfDoc.copyPages(originalPdfDoc, 
                    Array.from({length: range.end - range.start + 1}, (_, i) => range.start - 1 + i));
                
                pages.forEach(page => newPdfDoc.addPage(page));
                
                // 保存新PDF
                const newPdfBytes = await newPdfDoc.save();
                
                // 下载文件
                download(newPdfBytes, `${fileName}_${range.start}-${range.end}.pdf`, "application/pdf");
            }
        }
        
        // 显示/隐藏加载指示器
        function showLoading(show) {
            document.getElementById('loading').style.display = show ? 'block' : 'none';
            document.getElementById('splitBtn').disabled = show;
        }
        
        // 显示状态信息
        function showStatus(message, type) {
            const statusDiv = document.getElementById('status');
            statusDiv.textContent = message;
            statusDiv.className = type;
            statusDiv.style.display = 'block';
        }
        
        // 重置表单
        function resetForm() {
            document.getElementById('pdfFile').value = '';
            document.getElementById('pdfInfo').style.display = 'none';
            document.getElementById('splitBtn').disabled = true;
            document.getElementById('status').style.display = 'none';
            pdfBytes = null;
            totalPages = 0;
            fileName = '';
            
            const rangeContainer = document.getElementById('rangeContainer');
            rangeContainer.innerHTML = `
                <div class="range-row">
                    <span>范围 1:</span>
                    <input type="number" class="start-page" placeholder="起始页" min="1">
                    <span>至</span>
                    <input type="number" class="end-page" placeholder="结束页" min="1">
                    <button class="remove-range" onclick="removeRange(this)">×</button>
                </div>
            `;
            rangeCounter = 1;
        }
    </script>
</body>
</html>